import requests
from typing import List
from flask import Blueprint, request, jsonify
from sqlalchemy.orm import Session
from model import engine

# 测试任务蓝图
from model import Task
from utils.log_util import logger

task_bp = Blueprint('task_bp', __name__, url_prefix='/api/task')


@task_bp.route('/add', methods=['POST'])
def add():
    """
    新增
    :return:
    """
    resp = {
        'success': False,
        'msg': '',
        'data': []
    }

    try:
        # 解析请求数据
        req_data = request.json

        # 实例化模型对象
        task = Task(**req_data)

        # 写入数据库
        with Session(engine) as db_session:
            db_session.add(task)
            db_session.commit()

        # 组装响应数据
        resp.update({'success': True, 'msg': '新增成功'})

    except Exception as e:
        logger.warning(f'新增失败，原因：{e}')
        resp.update({'msg': f'新增失败，原因：{e}'})

    return jsonify(resp)


@task_bp.route('/list', methods=['GET'])
def list():
    """
    查询
    :return:
    """

    resp = {
        'success': False,
        'msg': '',
        'data': []
    }

    try:
        # 查询数据库记录
        with Session(engine) as session:
            tasks: List[Task] = session.query(Task).all()
            logger.info(tasks)

        # 组装响应数据
        for task in tasks:
            task.rate = f'{task.rate:.2%}'
        data = [task.as_dict() for task in tasks]
        resp.update({'success': True,
                     'data': data,
                     'msg': '查询成功',
                     'count': len(tasks)})

    except Exception as e:
        logger.warning(f'查询失败，原因：{e}')
        resp.update({'msg': f'查询失败，原因：{e}'})

    return jsonify(resp)


@task_bp.route('/execute', methods=['POST'])
def execute():
    """
    批量执行用例
    :return:
    """
    resp = {
        'success': False,
        'msg': '',
        'data': []
    }

    try:
        # 解析请求数据
        req_data = request.json
        logger.info(req_data)

        testcases = req_data['testcases']

        results = []
        success_count = 0
        for testcase in testcases:
            # 调用接口
            r = requests.request(method=testcase.get('method'),
                                 url=testcase.get('url'),
                                 params=testcase.get('params'),
                                 data=testcase.get('data'))
            results.append({'id': testcase.get('id'),
                            'result': r.json()})
            if r.status_code == 200:
                success_count += 1

        # 记录结果
        name = testcase.get('name')
        success = success_count
        total = len(testcases)
        rate = round(success / total, 2)

        task = Task(name=name, success=success, total=total, rate=rate)
        with Session(engine) as session:
            session.add(task)
            session.commit()

        # 组装响应结果
        resp.update({'success': True, 'data': results})

    except Exception as e:
        logger.warning(f'执行失败，原因：{e}')

    return jsonify(resp)